package main

import (
	"context"
	"fmt"
	"time"

	"github.com/TencentBlueKing/bkmonitor-kits/metricsdk"
	stdout "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
	controller "go.opentelemetry.io/otel/sdk/metric/controller/basic"
	processor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
	"go.opentelemetry.io/otel/sdk/metric/selector/simple"
	"go.opentelemetry.io/otel/sdk/resource"
)

func main() {
	// 按需设置 endpoint
	// grpcexporter "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
	// grpcexporter.WithEndpoint("ip:port")
	//
	// httpexporter "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
	// httpexporter.WithEndpoint("ip:port")
	//
	// 上报需要 dataid/access_token 鉴权 所以要注入环境变量 可在 saas 页面上注册获取
	// OTEL_RESOURCE_ATTRIBUTES="dataid=xxxx,access_token=yyyyy"
	//
	// 测试时可使用 stdout.WithPrettyPrint() 输出至终端
	exporter, err := stdout.New(stdout.WithPrettyPrint())
	if err != nil {
		panic(err)
	}

	cont := controller.New(
		processor.NewFactory(simple.NewWithInexpensiveDistribution(), exporter),
		controller.WithExporter(exporter),
		controller.WithCollectPeriod(10*time.Second), // 上报周期
		controller.WithResource(resource.Default()),  // <- 设置默认 resource.Default()
	)
	if err := cont.Start(context.Background()); err != nil {
		fmt.Println("failed to start controller:", err)
	}
	// 设置 instrumentation 相关信息
	metricsdk.SetMeterProvider(cont, "tencent.blueking.components")

	// 清理工作
	defer func() {
		if err := cont.Stop(context.Background()); err != nil {
			fmt.Println("failed to stop the metric controller:", err)
		}
	}()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute*10)
	defer cancel()

	// 注册全局 *Vec
	registerVec()
	go work(ctx)

	<-ctx.Done()
}
